<template>
  <div class="box22">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch">
      <el-form-item label="名称" prop="deviceName">
        <el-select v-model="queryParams.deviceName" placeholder="请选择名称" clearable>
          <el-option v-for="dict in dict.type.device_name" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="时间">
        <el-date-picker v-model="daterangeRecordTime" style="width: 240px" value-format="yyyy-MM-dd" type="daterange"
          range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['system:on:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['system:on:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['system:on:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['system:on:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="onList" @selection-change="handleSelectionChange"
      :header-cell-style="{ background: '#1890ff', color: '#fff' }">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="名称" align="center" prop="deviceName">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.device_name" :value="scope.row.deviceName" />
        </template>
      </el-table-column>
      <el-table-column label="能耗（KWH）" align="center" prop="consumption" />
      <el-table-column label="占比(%)" align="center" prop="consumProportion" />
      <el-table-column label="时间" align="center" prop="recordTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.recordTime, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <el-table-column label="产量(个)" align="center" prop="productNum" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['system:on:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['system:on:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-table v-loading="loading" :data="monthConsum" @selection-change="handleSelectionChange"
      :header-cell-style="setHeader" :cell-style="setCell">
      <el-table-column prop="deviceName" label="统计项"></el-table-column>
      <el-table-column label="能耗（KWH）" align="center" prop="consumption" />
      <el-table-column label="时间" align="center" prop="recordTime" width="180">
        <!-- <template slot-scope="scope">
          <span>{{ parseTime(scope.row.recordTime, "{y}-{m}") }}</span>
        </template> -->
      </el-table-column>
      <el-table-column label="产量(个)" align="center" prop="productNum" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['system:on:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['system:on:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />
    <h2 style="margin-top: 120px">能耗与产量数据图</h2>
    <el-select v-model="deviceForm.value" placeholder="请选择设备">
      <el-option label="导热油化蜡" value="导热油化蜡"></el-option>
      <el-option label="网带线一" value="网带线一"></el-option>
      <el-option label="压蜡柱机（A）" value="压蜡柱机（A）"></el-option>
      <el-option label="压蜡柱机（B）" value="压蜡柱机（B）"></el-option>
      <el-option label="螺旋提升线1" value="螺旋提升线1"></el-option>
      <el-option label="制冷机组1" value="制冷机组1"></el-option>
      <el-option label="发泡蜡设备-发泡灌装机" value="发泡蜡设备-发泡灌装机"></el-option>
      <el-option label="预热罩" value="预热罩"></el-option>
      <el-option label="自动上线" value="自动上线"></el-option>
      <el-option label="总计" value="总计"></el-option>
    </el-select>
    <el-button type="primary" @click="selectList">查询</el-button>
    <p>当前设备:{{ this.deviceForm.value }}</p>

    <div class="echartsVW" ref="echarts1"></div>
    <div class="sele">
      <span class="demonstration">请选择需要查询的天数范围</span>
      <el-select v-model="value" placeholder="请选择" @change="getCount">
        <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value">
        </el-option>
      </el-select>
    </div>
    <div class="echartsVW" ref="echarts2"></div>
    <div class="echartsVW" ref="echarts3"></div>

    <div class="echartsVW" ref="echarts4"></div>
    <div class="echartsVW" ref="echarts5"></div>

    <!-- 添加或修改能耗与产量对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="名称" prop="deviceName">
          <el-select v-model="form.deviceName" placeholder="请选择名称">
            <el-option v-for="dict in dict.type.device_name" :key="dict.value" :label="dict.label" :value="dict.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="能耗（KWH）" prop="consumption">
          <el-input v-model="form.consumption" placeholder="请输入能耗" />
        </el-form-item>
        <el-form-item label="时间" prop="recordTime">
          <el-date-picker clearable v-model="form.recordTime" type="date" value-format="yyyy-MM-dd" placeholder="请选择时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="产量(个)" prop="productNum">
          <el-input v-model="form.productNum" placeholder="请输入产量" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import * as echarts from "echarts";
import {
  listOn,
  getOn,
  delOn,
  addOn,
  updateOn,
  consumAndProNLine,
  monthConsumAPI,
  compareAPI,
  compareToNumAPI
} from "@/api/system/on";
import registerVue from "../../register.vue";

export default {
  name: "On",
  dicts: ["device_name"],
  data() {
    return {
      options: [
        {
          value: '30',
          label: '30天内'
        }, {
          value: '60',
          label: '60天内'
        }, {
          value: '90',
          label: '90天内'
        }],
      value: '30',
      deviceForm: {
        value: "总计",
      },
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 能耗与产量表格数据
      onList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 产量时间范围
      daterangeRecordTime: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 9,
        deviceName: null,
        consumption: null,
        recordTime: null,
        productNum: null,
      },
      // 当月总计
      monthConsum: [],
      // 表单参数
      form: {},
      // 表单校验
      rules: {},
    };
  },
  created() {
    this.getList();
    let obj = {};
    let arr = [];
    ({ foo: obj.prop, bar: arr[0] } = { foo: 123, bar: true });
  },
  mounted() {
    this.echarts1();
    this.getCount();
    this.monthConsumFn();
  },
  methods: {
    getCount() {
      this.echarts2();
      this.echarts3();
      this.echarts4();
      this.echarts5();
    },
    setCell({ row, column, rowIndex, columnIndex }) {
      // console.log(columnIndex, column, "2222");
      if (columnIndex === 0) {
        return `padding-left:11.7%;`;
      }
      if (columnIndex === 1) {
        return `padding-left:4%;`;
      }
      if (columnIndex === 2) {
        return `padding-left:3.5%;`;
      }
      if (columnIndex === 3) {
        return `padding-left:2%;`;
      }
      if (columnIndex === 4) {
        return `padding-left:1%;`;
      }
    },
    setHeader({ row, column, rowIndex, columnIndex }) {
      if (columnIndex === 0) {
        return `padding-left:12.5%;color :#1890ff`;
      }
      if (columnIndex === 1) {
        return `padding-left:4%;color :#1890ff`;
      }
      if (columnIndex === 2) {
        return `padding-left:3%;color :#1890ff`;
      }
      if (columnIndex === 3) {
        return `padding-left:2%;color :#1890ff`;
      }
      if (columnIndex === 4) {
        return `color :#1890ff`;
      }
    },

    selectList() {
      this.echarts1();
    },
    echarts1() {
      consumAndProNLine(this.deviceForm.value).then((res) => {
        // console.log(res.data);
        const e = echarts.init(this.$refs.echarts1);
        const colors = ["#1890ff", "red", "green"];
        const option = {
          color: colors,
          tooltip: {
            trigger: "axis",
            axisPointer: {
              type: "cross",
            },
          },
          legend: {
            data: ["能耗(KWH)", "产能(个）", "蜡重（KG）"],
          },
          xAxis: [
            {
              name: "时间",
              type: "category",
              axisTick: {
                alignWithLabel: true,
              },
              // prettier-ignore
              data: res.data[3],
            },
          ],
          yAxis: [
            {
              type: "value",
              name: "产能(个）",
              position: "right",
              alignTicks: true,
              axisLine: {
                show: true,
                lineStyle: {},
              },
              axisLabel: {
                formatter: "{value}",
              },
            },
            {
              type: "value",
              alignTicks: true,
              axisLine: {
                show: true,
                lineStyle: {},
              },
            },
            {
              type: "value",
              name: "能耗(KWH)",
              position: "left",
              alignTicks: true,
              axisLine: {
                show: true,
                lineStyle: {
                  color: "#6a7985",
                },
              },
              axisLabel: {
                formatter: "{value}",
              },
            },
            // {
            //   type: "value",
            //   name: "能耗2",
            //   position: "right",
            //   alignTicks: true,
            //   axisLine: {
            //     show: true,
            //     lineStyle: {
            //       color: "yellow",
            //     },
            //   },
            //   axisLabel: {
            //     formatter: "{value}",
            //   },
            // },
          ],
          series: [
            {
              name: "产能(个）",
              type: "bar",
              data: res.data[1],
            },
            {
              name: "能耗(KWH)",
              type: "line",
              yAxisIndex: 2,
              data: res.data[0],
            },
            {
              name: "蜡重（KG）",
              type: "bar",
              data: res.data[2],
              emphasis: {
                focus: "series",
              },
              markLine: {
                lineStyle: {
                  type: "dashed",
                },
                // data: [[{ type: "min" }, { type: "max" }]],
              },
            },
          ],
        };
        e.setOption(option);
        window.addEventListener("resize", function () {
          e.resize();
        });
      });
    },
    echarts2() {
      compareAPI(this.value).then((res) => {
        // console.log(res);
        var myChart = echarts.init(this.$refs.echarts2);
        var option;
        option = {
          legend: {
            data: ["生产数量与能耗比（个/KWH）"],
          },
          tooltip: {
            trigger: "axis",
            axisPointer: {
              type: "cross",
            },
          },
          xAxis: {
            type: 'category',
            data: res.data[2]
          },
          yAxis: {
            type: 'value'
          },
          series: [
            {
              name: '生产数量与能耗比（个/KWH）',
              data: res.data[0],
              type: 'line'
            }
          ]
        };

        option && myChart.setOption(option);
        window.addEventListener("resize", function () {
          myChart.resize();
        });
      });
    },
    echarts3() {
      compareAPI(this.value).then((res) => {
        // console.log(res);
        var myChart = echarts.init(this.$refs.echarts3);
        var option;
        option = {
          legend: {
            data: ["生产蜡重与能耗比（kg/KWH）"],
          },
          tooltip: {
            trigger: "axis",
            axisPointer: {
              type: "cross",
            },
          },
          xAxis: {
            type: 'category',
            data: res.data[2]
          },
          yAxis: {
            type: 'value'
          },
          series: [
            {
              name: '生产蜡重与能耗比（kg/KWH）',
              data: res.data[1],
              type: 'line'
            }
          ]
        };

        option && myChart.setOption(option);
        window.addEventListener("resize", function () {
          myChart.resize();
        });
      });
    },
    echarts4() {
      compareToNumAPI(this.value).then((res) => {
        // console.log(res);
        var myChart = echarts.init(this.$refs.echarts4);
        var option;
        option = {
          legend: {
            data: ["能耗与生产数量比（KWH/1000个）"],
          },
          tooltip: {
            trigger: "axis",
            axisPointer: {
              type: "cross",
            },
          },
          xAxis: {
            type: 'category',
            data: res.data[2]
          },
          yAxis: {
            type: 'value'
          },
          series: [
            {
              name: '能耗与生产数量比（KWH/1000个）',
              data: res.data[0],
              type: 'line'
            }
          ]
        };

        option && myChart.setOption(option);
        window.addEventListener("resize", function () {
          myChart.resize();
        });
      });
    },
    echarts5() {
      compareToNumAPI(this.value).then((res) => {
        // console.log(res);
        var myChart = echarts.init(this.$refs.echarts5);
        var option;
        option = {
          legend: {
            data: ["能耗与生产蜡重比（KWH/1000kg）"],
          },
          tooltip: {
            trigger: "axis",
            axisPointer: {
              type: "cross",
            },
          },
          xAxis: {
            type: 'category',
            data: res.data[2]
          },
          yAxis: {
            type: 'value'
          },
          series: [
            {
              name: '能耗与生产蜡重比（KWH/1000kg）',
              data: res.data[1],
              type: 'line'
            }
          ]
        };

        option && myChart.setOption(option);
        window.addEventListener("resize", function () {
          myChart.resize();
        });
      });
    },
    /** 查询能耗与产量列表 */
    getList() {
      this.loading = true;
      this.queryParams.params = {};
      if (null != this.daterangeRecordTime && "" != this.daterangeRecordTime) {
        this.queryParams.params["beginRecordTime"] =
          this.daterangeRecordTime[0];
        this.queryParams.params["endRecordTime"] = this.daterangeRecordTime[1];
      }
      listOn(this.queryParams).then((response) => {
        // console.log(response, '----------');
        this.onList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    monthConsumFn() {
      monthConsumAPI().then((res) => {
        this.monthConsum = res.data;
        // console.log(res);
        this.monthConsum.forEach((item) => {
          if (item.recordTime !== null) {
            // this.$set(
            //   // this.monthConsum[0],
            //   "recordTime",
            //   item.recordTime.substr(0, 7)
            // );
            // 只显示月份  substr函数截取字符串
            this.$set(item, "recordTime", item.recordTime.substr(0, 7));
          }
        });
        // console.log(res.data, "2222");
        // console.log(this.monthConsum, "@@@");
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        deviceNo: null,
        deviceName: null,
        consumption: null,
        recordTime: null,
        productNum: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.daterangeRecordTime = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加能耗与产量";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getOn(id).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = "修改能耗与产量";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.id != null) {
            updateOn(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addOn(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm('是否确认删除能耗与产量编号为"' + ids + '"的数据项？')
        .then(function () {
          return delOn(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "system/on/export",
        {
          ...this.queryParams,
        },
        `on_${new Date().getTime()}.xlsx`
      );
    },
  },
};
</script>
<style scoped>
.box22>>>.el-table {
  margin-bottom: 38px;
}

.echartsVW {
  width: 100%;
  height: 400px;
  margin-top: 30px;
}

.box22 {
  margin-top: 20px;
  margin-left: 30px;
  margin-right: 30px;
  margin-bottom: 50px;
}
.demonstration{
  margin-left: 30px;
    margin-right: 20px;
}
/* .title1 {
  margin-top: 70px;
  color: #409eff;
}
.title2 {
  font-size: 16px;
} */
</style>
